/*
 * Copyright (c) 2013 Andaily Information Technology Co. Ltd
 * www.andaily.com
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of
 * Andaily Information Technology Co. Ltd ("Confidential Information").
 * You shall not disclose such Confidential Information and shall use
 * it only in accordance with the terms of the license agreement you
 * entered into with Andaily Information Technology Co. Ltd.
 */
package top.suven.http.oauth.validator;

import org.apache.oltu.oauth2.as.request.AbstractOAuthTokenRequest;
import org.apache.oltu.oauth2.common.exception.OAuthSystemException;
import org.apache.oltu.oauth2.common.message.OAuthResponse;
import top.suven.http.oauth.vo.OAuthTokenBuilder;


/**
 * 2018-08-01
 * <p/>
 *  AbstractOauthTokenValidator
 *  *  客户端	客户详细资料 抽像模块类，用于公共验证和获取客户用户的信息；
 *  * 将通用的行为(方法) 位于此
 *
 * @author suven.wang
 */
public abstract class AbstractOauthGrantTypeValidator extends AbstractOAuthTypeValidator {


    protected AbstractOAuthTokenRequest oauthRequest;

    protected AbstractOauthGrantTypeValidator(AbstractOAuthTokenRequest tokenRequest) {
        super(tokenRequest);
        this.oauthRequest = tokenRequest;

    }

    protected String grantType() {
        return oauthRequest.getGrantType();
    }

    protected String getCode() {
        return oauthRequest.getCode();
    }

    /**
     * 获取请求用户随机码
     * @return
     */
//    protected String getState() {
//        return oauthRequest.get
//    }

    protected boolean validateGrantType() throws OAuthSystemException {
        //1.校验客户端clientId是否正确  validate()
        //2.检查客户端grant_type是否正确
        final String grantType = grantType();
        if (!clientDetails.grantTypes().contains(grantType)) {
            logger.debug("Invalid grant_type '{}', client_id = '{}'", grantType, clientDetails.getClientId());
            OAuthResponse response = invalidGrantTypeResponse(grantType);
            this.setResponse(response);
            return false;
        }
        return true;
    }


    //true is invalided
    protected long validateUsernamePassword() {
        final String username = oauthRequest.getUsername();
        final String password = oauthRequest.getPassword();
        try {
            if (null == username || null == password ) {
                setUserPasswordResponse();
                return 0;
            }
            long userId = oauthService.checkUserInfoByNameAndPw(username,password);
            if(userId > 0 ){
                return userId;
            }
            setUserPasswordResponse();
            return 0;
        } catch (Exception e) {
            logger.debug("Login failed by username: " + username, e);
            try {
                setUserPasswordResponse();
            } catch (OAuthSystemException e1) {
            }

        }
        return 0;
    }
    private void setUserPasswordResponse() throws OAuthSystemException{
        OAuthResponse response = invalidUsernamePasswordResponse();
        this.setResponse(response);
    }

    /**
     * 校验
     *
     * @return
     * @throws OAuthSystemException
     */
    protected boolean validateRefreshToken() throws OAuthSystemException {
        //to do
        //validate refresh_token
        final String refreshToken = oauthRequest.getRefreshToken();
        String redirectURI = oauthRequest.getRedirectURI();

        OAuthTokenBuilder accessToken = this.refreshToken(refreshToken);
        if (accessToken == null ) {
            logger.info("Invalid refresh_token: '{}'", refreshToken);
            OAuthResponse response = invalidRefreshTokenResponse(refreshToken);
            this.setResponse(response);
            return false;
        }//返回token
        responseToken(accessToken);
        return true;
    }

    /**
     * 校验生成返回token,并保存
     *
     * @return
     * @throws OAuthSystemException
     */
    protected boolean validateAccessToken(long userId) throws OAuthSystemException {
        //to do
        //validate refresh_token
        OAuthTokenBuilder accessToken = this.saveToken(userId);
        if(null == accessToken){//返回token
            OAuthResponse response = invalidTokenResponse(this.getUserId());
            this.setResponse(response);
            return false;
        }
        responseToken(accessToken);
        return true;
    }




}
